﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace NovelTools
{
	class Program
	{
		class NavelModel
		{
			public string HandLine { get; set; }
			public List<string> Section { get; set; }

			public void SetModel(string handLine, List<string> section)
			{
				HandLine = handLine;
				Section = section;
			}
		}

		private static string filePath = string.Empty;
		private static string[] lines;
		private static NavelModel novel = new NavelModel();
		private static Dictionary<long, NavelModel> novels = new Dictionary<long, NavelModel>();
		private static Dictionary<long, List<string>> repeatSection = new Dictionary<long, List<string>>();
		private static List<long> lackSection = new List<long>();
		private static Dictionary<long, string> exceptionSection = new Dictionary<long, string>();
		private static long maxSection = 0;

		static void Main(string[] args)
		{
			filePath = InputFilePath();
			lines = LoadFile(filePath);
			DisposeLines(lines);
			ShowInfo();
			Instruct();
			Console.ReadKey();
		}

		private static string InputFilePath()
		{
			Console.WriteLine("输入文件路径：");
			return Console.ReadLine();
			//return "C:\\Users\\Vermandois\\Desktop\\唐朝好地主.txt";
			//return "C:\\Users\\Vermandois\\Desktop\\调教大宋.txt"; 
			//return "C:\\Users\\Vermandois\\Desktop\\校花的贴身高手.txt";
		}

		private static string[] LoadFile(string filePath)
		{
			Console.WriteLine("文件路径：" + filePath);
			return File.ReadAllLines(@filePath, Encoding.UTF8);
		}

		private static void DisposeLines(string[] lines)
		{
			List<string> section = new List<string>();
			long index = 0;
			bool ignore = true;
			foreach (string line in lines)
			{
				Regex regex = new Regex("第([\\s\\S]{1,5})章", RegexOptions.Multiline);
				MatchCollection match = regex.Matches(line);

				if (match.Count > 0 && !line.StartsWith("    "))
				{
					string value = match[0].Groups[1].Value;
					index = ToIntHelper.ParseCnToInt(value);
					if (index <1)
						return;
					if (novels.ContainsKey(index))
					{
						ignore = true;
						if (repeatSection.ContainsKey(index))
						{
							repeatSection[index].Add(line);
						}
						else
						{
							repeatSection.Add(index, new List<string> { novels[index].HandLine });
							repeatSection[index].Add(line);
						}
					}
					else
					{
						string hl = line.Replace(value, index.ToString());
						novels.Add(index, new NavelModel { HandLine = hl, Section = new List<string>() });
						ignore = false;
						if (index > maxSection)
						{
							maxSection = index;
						}
					}
				}
				else
				{
					if (!ignore)
					{
						novels[index].Section.Add(line);
					}
				}
				
			}
		}

		private static void ShowInfo()
		{
			Console.WriteLine($" === 最大章节数：{ maxSection } === ");
			Console.WriteLine($" === 实际章节数：{ novels.Count } === ");
			CheckRepeatSection();
			CheckLackSection();
			CheckExceptionSection();
		}

		private static void CheckRepeatSection()
		{
			Console.WriteLine($" === 重复章节数：{ repeatSection.Count } === ");
			var dicSort = repeatSection.OrderBy(section => section.Key);
			foreach (var kv in dicSort)
			{
				List<string> hs = new List<string>();
				foreach (var h in kv.Value)
				{
					if (!hs.Contains(h))
					{
						hs.Add(h);
					}
				}

				string hls = string.Empty;
				bool isInit = false;
				if (hs.Count>1)
				{
					foreach (var h in hs)
					{
						if (!isInit)
						{
							isInit = true;
							hls += $"{h} ===>";
						}
						else
						{
							hls += $" #{h}# ";
						}

					}
				}
				else
				{
					hls = hs[0];
				}
				

				Console.WriteLine($"{kv.Key} {hls}");
			}

		}

		private static void CheckLackSection()
		{
			if (maxSection == novels.Count)
			{
				return;
			}

			if (maxSection > novels.Count)
			{
				for (long i = 1; i < maxSection + 1; i++)
				{
					lackSection.Add(i);
				}
				foreach (var index in novels.Keys)
				{
					lackSection.Remove(index);
				}
			}
			else
			{
				Console.WriteLine("???");
			}
			Console.WriteLine($" === 缺少章节数：{ lackSection.Count } ===");
			foreach (var index in lackSection)
			{
				Console.WriteLine($"第{ index }章");
			}
		}

		private static void CheckExceptionSection()
		{
			foreach (var index in novels.Keys)
			{
				NavelModel model = novels[index];
				string section = string.Empty;
				foreach (var item in model.Section)
				{
					section += item;
				}
				if (model.Section.Count <= 3 && section.Length < 500)
				{
					exceptionSection.Add(index, model.HandLine);
				}
			}
			Console.WriteLine($" === 异常章节数：{ exceptionSection.Count } ===");
			foreach (var index in exceptionSection.Keys)
			{
				Console.WriteLine($"第{ index }章 { exceptionSection[index] }");
			}
		}

		private static void Instruct()
		{
			Console.WriteLine("Instruct：");
			var ins = Console.ReadLine();
			var kv = ins.Split(' ');
			switch (kv[0])
			{
				case "-l"://查看 -l 123
					LookSection(kv[1]);
					break;
				case "-r"://替换 -r 123
					break;
				case "-q"://退出 -q
					return;
				case "-i"://插入章节 -i 123
					return;
				case "-c"://创建修正后的文本 -c
					CreatNewNoval(filePath);
					break;
				default:
					break;
			}
			Instruct();
		}

		private static void LookSection(string index)
		{
			long idx = ToIntHelper.ParseCnToInt(index);
			if (idx > 0)
			{
				if (novels.ContainsKey(idx))
				{
					Console.WriteLine(novels[idx].HandLine);
					foreach (var s in novels[idx].Section)
					{
						Console.WriteLine(s);
					}
				}
			}
		}

		private static void CreatNewNoval(string oldFilePath)
		{
			int index = oldFilePath.Length - 4;
			string newPath = oldFilePath.Insert(index,"(修正)");

			var temp = novels.OrderBy(section => section.Key);

			FileStream fs1 = new FileStream(newPath, FileMode.OpenOrCreate, FileAccess.Write);//创建写入文件 
			StreamWriter sw = new StreamWriter(fs1);
			foreach (var item in temp)
			{
				sw.WriteLine(item.Value.HandLine);//开始写入值
				foreach (var s in item.Value.Section)
				{
					sw.WriteLine(s);
				}
			}
			sw.Close();
			fs1.Close();
		}


	}
}
